package com.itao.springboot.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sjt
 * @Date 2024/12/6 15:17
 */
@Configuration
public class ControllerConfig {

    @Bean("/hello")
    public Controller helloController(){

        return (request, response) -> {
            // 创建一个 Map 来存储要返回的数据
            Map<String, Object> model = new HashMap<>();
            model.put("key", "value");
            model.put("number", 123);
            model.put("name", null);

            // 创建一个 MappingJackson2JsonView 实例
            MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
            // 忽略null值
            jsonView.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
            // 返回 ModelAndView，指定视图和模型数据
            return new ModelAndView(jsonView, model);
        };
    }
}
